<template>
    <div>
        <el-card shadow="never">
            <template slot="header">
                <span>商家</span>
            </template>
            <Search :search-options="searchOptions" @search="handleSearch">
                <template #customSelectSlot="{ form }">
                    <el-select v-model="applet_id" placeholder="请选择" @change="merchantChange" style="width: 180px">
                        <el-option v-for="item in mini_options" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </template>
                <template slot="extra-buttons">
                    <el-button type="primary" v-if="userInfo.identity == 1" @click="add">添加商家</el-button>
                </template>

            </Search>
            <el-table v-loading="listLoading" element-loading-text="数据正在加载中" :data="data" border fit
                highlight-current-row style="width: 100%">
                <el-table-column v-for="item in columns" :key="item.prop" :label="item.label" :prop="item.prop"
                    :align="item.align">
                    <template slot-scope="{ row }">
                        <div v-if="item.prop === 'logo'">
                            <el-image style="width: 100px; height: 100px" :src="row.logo | filter_img"
                                :preview-src-list="[row.logo]">
                                <div slot="error" class="image-slot">
                                    <i class="el-icon-picture-outline"></i>
                                </div>
                            </el-image>
                        </div>
                        <div v-else-if="item.prop === 'business_license'">
                            <el-image style="width: 100px; height: 100px" :src="row.business_license | filter_img"
                                :preview-src-list="[row.logo]">
                                <div slot="error" class="image-slot">
                                    <i class="el-icon-picture-outline"></i>
                                </div>
                            </el-image>
                        </div>
                        <div v-else-if="item.prop === 'categories'">
                            <el-tag style="margin: 2px;" v-for="i in row.categories" :key="i.id">{{ i.name }}</el-tag>
                        </div>
                        <div v-else-if="item.prop === 'delivery_range'">
                            <p>{{ row.delivery_range }}公里</p>
                            <p>满{{ row.free_delivery_amount }}免费配送</p>
                        </div>
                        <div v-else-if="item.prop === 'status'">
                            <el-tag :type="row.status == 1 ? 'success' : 'danger'">{{ row.status == 1 ? '营业中' : '休息中'
                                }}</el-tag>
                        </div>
                        <div v-else>
                            {{ row[item.prop] }}
                        </div>
                    </template>
                </el-table-column>

                <el-table-column label="操作" width="300" align="center">
                    <template slot-scope="{ row }">
                        <el-button type="primary" size="mini" @click="handleEdit(row)" v-auth="'edit'">
                            编辑
                        </el-button>
                        <el-button type="danger" size="mini" @click="handleDel(row)" v-auth="'del'">
                            删除
                        </el-button>
                        <el-button type="primary" size="mini" @click="copyFn(row)" v-if="userInfo.identity == 1">
                            复制
                        </el-button>
                        <el-button type="primary" size="mini" @click="bind(row)">
                            绑定列表
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <Pagination :page="page" :page_size="page_size" :total="total" @sizeChange="sizeChange"
                @currentChange="pageChange" />
        </el-card>
        <AddOrEdit ref="AddOrEditRef" @refresh="pageChange" :applet_id="applet_id" :printerList="printList"
            :payList="payList" :categoryList="categoryList" />
        <el-dialog :visible.sync="isShowMoreTableModal" title="绑定列表" width="70%">
            <div>
                <el-button type="primary" size="mini" @click="BindAdminStatus()">绑定</el-button>
            </div>
            <!-- 选择绑定的管理员列表 -->
            <el-dialog width="40%" title="绑定管理员" :visible.sync="innerAdminVisible" append-to-body
                :before-close="closeBindModal">
                <el-select v-model="admin_id" placeholder="请选择" style="width: 100%">
                    <el-option v-for="item in admin_options" :key="item.id" :label="item.label" :value="item.value">
                    </el-option>
                </el-select>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="closeBindModal">取 消</el-button>
                    <el-button type="primary" @click="submitBindAdminStatus">确 定</el-button>
                </div>
            </el-dialog>
            <!-- 获取小程序绑定的管理员列表 -->
            <el-table :data="merchantBindList" height="400px">
                <el-table-column v-for="item in BindAdminColumns" :key="item.prop" :label="item.label" :prop="item.prop"
                    :align="item.align">

                    <template slot-scope="{ row, $index }">
                        <div v-if="item.slot === 'status'">
                            <el-tag :type="row.status | statusFilter">
                                {{ row.status | statusTextFilter }}
                            </el-tag>
                        </div>
                        <div v-else-if="item.prop === 'avatar'">
                            <el-image style="width: 100px; height: 100px" :src="row[item.prop] | filter_img"></el-image>
                        </div>
                        <div v-else-if="item.slot === 'index'">{{ $index + 1 }}</div>
                        <div v-else>{{ row[item.prop] }}</div>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="230">
                    <template slot-scope="{ row }">
                        <div>
                            <el-button type="danger" size="mini" @click="unbindMerchant(row)">解绑</el-button>
                        </div>

                    </template>
                </el-table-column>
            </el-table>
        </el-dialog>
        <!-- 复制 -->
        <el-dialog :visible.sync="isShowCopyMerchantModal" title="复制" width="50%">
            <div>
                <el-select  v-model="copyMerchant"
                placeholder="请选择" clearable
                style="width: 100%;">
                <el-option v-for="option in copyMerchantOptions" :key="option.value" :label="option.label" :value="option.value" />
                </el-select>
            </div>
              <span slot="footer" class="dialog-footer">
                <el-button @click="cancelCopy()">取 消</el-button>
                <el-button type="primary" @click="handleCopy()">复 制</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import Search from '@/components/Search.vue';
import Pagination from '@/components/Pagination.vue';
import { SEARCH_OPTIONS, columns } from './options';
import { merchantDelete, merchantList, getMiniAppList, getMerchantCategoryList, copyMerchant, getMerchantAdmins, merchantBindAdmin, merchantunBindAdmin } from '../api';
import AddOrEdit from './AddOrEdit.vue';
import { printerList } from '@/views/Printer/api';
import { payConfigList } from '@/views/Pay/api';
import { getAdministratorList } from '@/views/system/api/user';
export default {
    data() {
        const user = JSON.parse(localStorage.getItem('user'));
        let options = SEARCH_OPTIONS
        if (user.identity === 3) {
            options = SEARCH_OPTIONS.filter(i => {
                if (i.identity) {
                    return i.identity.includes(user.identity)
                } else {
                    return true
                }
            })
        }
        return {
            isShowCopyMerchantModal: false,
            copyMerchantOptions: [],
            copyMerchant: '',
            currentMerchantItem: null,
            BindAdminColumns: [
                {
                    label: "序号",
                    type: "index",
                    slot: "index",
                    align: "center",
                },
                {
                    label: '用户名',
                    prop: 'nickname',
                    align: 'center'
                },
                {
                    label: '头像',
                    prop: 'avatar',
                    align: 'center',
                },
                {
                    label: '电话',
                    prop: 'mobile',
                    align: 'center'

                },
            ],
            userInfo: user,
            searchOptions: options,
            columns: columns,
            listLoading: false,
            data: [],
            page: 1,
            total: 0,
            page_size: 10,
            searchParmas: {},
            mini_options: [],
            applet_id: null,
            categoryList: [],
            printList: [],
            payList: [],
            isShowMoreTableModal: false,
            innerAdminVisible: false,
            admin_id: null,
            admin_options: [],
            merchantBindList: [],
            bindId: null,
        }
    },
    components: { Search, Pagination, AddOrEdit },
    created() {
        const p = { page: 1, page_size: 9999 }
        if (this.userInfo.identity != 3) {
            this.getMiniAppData();
            printerList(p).then(res => {
                this.printList = res.data.map(i => ({
                    value: i.id,
                    label: i.name
                }))
            }).catch(() => { })

            payConfigList(p).then(res => {
                this.payList = res.data.map(i => ({
                    label: i.title,
                    value: i.id
                }))
            })

            getMerchantCategoryList(p).then(r => {
                let arr = r.data || r.list;
                arr = arr.sort((a, b) => a.sort - b.sort);
                this.categoryList = arr.map(i => ({
                    label: i.name,
                    value: i.id
                }))
            })
        } else {
            this.init();
        }
        //identity: 2
        getAdministratorList({ ...p, identity: 3 }).then(res => {
            this.admin_options = res.data.map(i => ({
                label: i.nickname,
                value: i.id
            }))
        })


    },
    methods: {
        getMerchantBindList() {
            getMerchantAdmins({ merchant_id: this.bindId }).then(res => {
                this.merchantBindList = res.data;
            }).catch(() => { })
        },
        merchantChange(e) {
            this.applet_id = e;
            this.pageChange(1);
        },
        getMiniAppData() {
            const param = {
                page: 1,
                page_size: 999999,
            }
            getMiniAppList(param).then(res => {
                res.data = res.data.reverse()
                this.applet_id = res.data && res.data[0].id
                this.mini_options = res.data && res.data.map(item => {
                    return {
                        label: item.name,
                        value: item.id,
                    }
                })
                this.init();
            })
        },
        init() {
            let p = {
                page: this.page,
                page_size: this.page_size,
                ...this.searchParmas,
            }
            p.applet_id = this.applet_id
            merchantList(p).then(res => {
                console.log(222, res);
                this.total = res.total;
                this.data = res.data
                this.copyMerchantOptions = res.data && res.data.map(item=>{
                    return {
                        value: item.id,
                        label: item.name,
                    }
                })
            })
        },
        handleSearch(params) {
            console.log('.id', this.applet_id);

            this.searchParmas = params;
            // 执行搜索操作
            this.page = 1;
            this.init();
        },
        bind(data) {
            this.bindId = data.id;
            this.isShowMoreTableModal = true;
            getMerchantAdmins({ merchant_id: data.id }).then(res => {
                console.log(1111, res);
                
                this.merchantBindList = res;
            }).catch(() => {

            })
        },
        closeBindModal() {
            this.innerAdminVisible = false;
            this.admin_id = null;
        },
        submitBindAdminStatus() {
            let params = {
                merchant_id: this.bindId,
                admin_id: this.admin_id
            }
            merchantBindAdmin(params).then(res => {
                this.$message({
                    type: 'success',
                    message: '绑定成功!'
                })
                this.closeBindModal()
                this.getMerchantBindList();
            }).catch(() => { })

        },
        unbindMerchant(data) {
            merchantunBindAdmin({ merchant_id: this.bindId, admin_id: data.id }).then(res => {
                this.$message({
                    type: 'success',
                    message: '解绑成功!'
                })
                this.getMerchantBindList();
            }).catch(() => { })
        },
        BindAdminStatus() {
            this.innerAdminVisible = true;
        },
        copyFn(data) {
            console.log(data, 'fuzhi');
            this.currentMerchantItem = data
            this.isShowCopyMerchantModal = true
            let p = {
                page: 1,
                page_size: 99999,
                applet_id: this.applet_id
            }
            merchantList(p).then(res => {
                console.log(222, res);
                this.copyMerchantOptions = res.data && res.data.map(item=>{
                    return {
                        value: item.id,
                        label: item.name,
                    }
                })
            })
            // copy_merchant_id
           
            
        },
        handleCopy(){
            console.log('copy_merchant_id', this.copyMerchant);
            if(!this.copyMerchant) {
                this.$message.error('请选择需要复制的店铺!')
                return
            }
            copyMerchant({ target_merchant_id: this.currentMerchantItem.id, copy_merchant_id: this.copyMerchant }).then(res => {
                this.$message({
                    type: 'success',
                    message: '复制成功'
                })
                this.cancelCopy()
                this.pageChange(1);
            })
        },
        cancelCopy(){
            this.isShowCopyMerchantModal = false
            this.copyMerchant = ''
            this.currentMerchantItem = null
        },
        add() {
            this.$refs.AddOrEditRef.add();
        },
        handleEdit(data) {
            const category_ids = Array.isArray(data.categories) ? data.categories.map(i => i.id) : []
            const date = [data.business_start_time, data.business_end_time]
            this.$refs.AddOrEditRef.edit({ ...data, category_ids, date });
        },
        handleDel(data) {
            this.$confirm('确认删除该商户?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.listLoading = true;
                merchantDelete({ ids: data.id }).then(res => {
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    })
                    this.pageChange(1);
                }).finally(() => {
                    this.listLoading = false;
                })
            }).catch(() => { })
        },
        pageChange(page) {
            this.page = page;
            this.init();
        },
        sizeChange(size) {
            this.page_size = size;
            this.page = 1;
            this.init();
        },
    },
}
</script>

<style lang='scss' scoped></style>